    //
//  AppDelegate.m
//  JiuLe
//
//  Created by xcq on 15/10/31.
//  Copyright © 2015年 Fine. All rights reserved.
//
#import "Common.h"
#import "AppDelegate.h"
#import "JlUserManager.h"
#import <GTSDK/GeTuiSdk.h>
#import "BaseNavController.h"
#import "LoginViewController.h"
#import "UIColor+RGBConverHex.h"
#import "MessageViewController.h"
#import "JLContentViewController.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import "HomeViewController.h"
#import "IQKeyboardManager.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <UMSocialCore/UMSocialCore.h>
#import "WXApiManager.h"
#import <AlipaySDK/AlipaySDK.h>
#import "MallRequestManager.h"
#import "NSString+Check.h"
//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
#import <UserNotifications/UserNotifications.h>
//#endif

/// 个推开发者网站中申请App时注册的AppId、AppKey、AppSecret
#define kGtAppId           @"63GHvHb4Qr8cIluoXJF797"
#define kGtAppKey          @"w5FhVpAEBcAewXzpmEVHHA"
#define kGtAppSecret       @"gOQwA9qTBU9IiSaoby34g2"

//测试(20161207)推送测试证书密码  ：mdzz123  test.com.Jiule.JiuLe
//#define kGtAppId           @"Wnj7F9xzsv6dkbPgppUp73"
//#define kGtAppKey          @"WpLdDZcz8f93aOj97tryv1"
//#define kGtAppSecret       @"PWWhUuP7O7AiYIM3WBK206"

NSString *const NotificationCategoryIdent = @"ACTIONABLE";
NSString *const NotificationActionOneIdent = @"ACTION_ONE";
NSString *const NotificationActionTwoIdent = @"ACTION_TWO";

static BOOL isBackGround = NO;

@interface AppDelegate () <GeTuiSdkDelegate,UNUserNotificationCenterDelegate,UIAlertViewDelegate>
@property (nonatomic,strong)NSTimer *timer;
@end

@implementation AppDelegate
@synthesize receivedNotification = _receivedNotification;
@synthesize baseNav = _baseNav;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
     [NSThread sleepForTimeInterval:2.0];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    [AppDelegate chooseRootViewController];
    //在iOS中如果点击一个弹出通知（或者锁屏界面滑动查看通知），默认会自动打开当前应用。由于通知由系统调度那么此时进入应用有两种情况：如果应用程序已经完全退出那么此时会调用
    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (userInfo) {
        self.receivedNotification = YES;
    }
    [self.window makeKeyAndVisible];
    //个推
    [self initGePush:launchOptions];
    //重置角标
    [GeTuiSdk resetBadge];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    //友盟分享
    //打开调试日志
    [[UMSocialManager defaultManager] openLog:NO];
    //设置友盟appkey
    [[UMSocialManager defaultManager] setUmSocialAppkey:@"57fc52ec67e58e3aa20024ff"];
    NSLog(@"UMeng social version: %@", [UMSocialGlobal umSocialSDKVersion]);
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wxdc1e388c3822c80b" appSecret:@"3baf1193c85774b3fd9d18447d76cab0" redirectURL:@"http://mobile.umeng.com/social"];
    //设置新浪的appKey和appSecret
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:@"4266948771"  appSecret:@"6f9b13e2eb45f38f39314cbd75b2ffb8" redirectURL:@"http://sns.whalecloud.com/sina2/callback"];
    //设置分享到QQ互联的appKey和appSecret    
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"1105749546"  appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];
    //注册微信支付
     [WXApi registerApp:WX_APPID withDescription:@"demo 2.0"];
    return YES;
}

- (void)networkStateChange{
    [self checkNetworkState];
}

- (void)checkNetworkState{
         // 1.检测wifi状态
         Reachability *wifi = [Reachability reachabilityForLocalWiFi];
         // 2.检测手机是否能上网络(WIFI\3G\2.5G)
         Reachability *conn = [Reachability reachabilityForInternetConnection];
         // 3.判断网络状态
        if ([wifi currentReachabilityStatus] != NotReachable) {//有wifi
                NSLog(@"有wifi");
            [[NSUserDefaults standardUserDefaults]setObject:@"wifi" forKey:JiuLeNetBility];
        } else if ([conn currentReachabilityStatus] != NotReachable) { // 没有使用wifi, 使用手机自带网络进行上网
                NSLog(@"使用手机自带网络进行上网");
            [[NSUserDefaults standardUserDefaults]setObject:@"3g" forKey:JiuLeNetBility];
        } else { // 没有网络
                NSLog(@"没有网络");
            [[NSUserDefaults standardUserDefaults]setObject:@"none" forKey:JiuLeNetBility];
        }
}

+ (void)chooseRootViewController {
    NSString *userID = [[NSUserDefaults standardUserDefaults] objectForKey:UserDataID];
    NSString *passWord = [[NSUserDefaults standardUserDefaults] objectForKey:UserDataPassWord];
    NSNumber *FirstRun = [[NSUserDefaults standardUserDefaults] objectForKey:JiuLeFirstRun];
    if ((FirstRun == nil || [FirstRun isKindOfClass:[NSNull class]] || [FirstRun boolValue])) {
        //TODO去引导页
        JLContentViewController *jl = [[JLContentViewController alloc] init];
        [UIApplication sharedApplication].delegate.window.rootViewController = jl;
        return;
    }
    if ((userID != nil && ![userID isEqualToString:@""]) && (passWord != nil && ![passWord isEqualToString:@""])) {
        [AppDelegate goHomePage];
    } else {
        //进入登陆页面
        LoginViewController *login = getStoryOfControllerInstance(@"LoginViewController");
         BaseNavController *baseNavCT = [[BaseNavController alloc] initWithRootViewController:login];
        [UIApplication sharedApplication].delegate.window.rootViewController = baseNavCT;
    }
}

+ (void)goHomePage {
    HomeViewController *home = [[HomeViewController alloc]initWithNibName:@"HomeViewController" bundle:nil];
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.baseNav = [[BaseNavController alloc] initWithRootViewController:home];
    [UIApplication sharedApplication].delegate.window.rootViewController    = appDelegate.baseNav;
    
}

- (void)initGePush:(NSDictionary *)launchOptions {
    
    // 通过个推平台分配的appId、 appKey 、appSecret 启动SDK，注：该方法需要在主线程中调用
    [GeTuiSdk startSdkWithAppId:kGtAppId
                         appKey:kGtAppKey
                      appSecret:kGtAppSecret
                       delegate:self];
    //[1-2]:设置是否后台运行开关
    [GeTuiSdk runBackgroundEnable:YES];
    // 注册APNS
    [self registerUserNotification];
}

#pragma mark - 用户通知(推送) _自定义方法
/** 注册用户通知 */
- (void)registerUserNotification {
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
            if (!error) {
                NSLog(@"request authorization succeeded!");
            }
        }];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    } else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        // 定义用户通知设置 通知类型(Remote.远程 - Badge.标记 Alert.提示 Sound.声音)
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeAlert) categories:nil];
        //[[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    } else {
        // 定义远程通知类型(Remote.远程 - Badge.标记 Alert.提示 Sound.声音)
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }
}

#pragma mark - 用户通知(推送)回调 _IOS 8.0以上使用
/** 已登记用户通知 */
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
    // 注册远程通知（推送）
    [application registerForRemoteNotifications];
}

#pragma mark - 远程通知(推送)回调
/** 远程通知注册成功委托 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    _myToken = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    _myToken = [_myToken stringByReplacingOccurrencesOfString:@" " withString:@""];
    [GeTuiSdk registerDeviceToken:_myToken];    /// 向个推服务器注册deviceToken
    NSLog(@">>>[DeviceToken Success]:%@\n\n",_myToken);
}

/** 远程通知注册失败委托 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    [GeTuiSdk registerDeviceToken:@""];     /// 如果APNS注册失败，通知个推服务器
    NSLog(@"\n>>>[DeviceToken Error]:%@\n\n",error.description);
}

#pragma mark - APP运行中接收到通知(推送)处理
/** APP已经接收到“远程”通知(推送) - (App运行在后台/App运行在前台)*/
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    receivedNotification = YES;
}

/** APP已经接收到“远程”通知(推送) - 透传推送消息*/
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
    JLLog(@"--------------------------- 推送来啦 ----------------------------");
    receivedNotification = YES;
    completionHandler(UIBackgroundFetchResultNewData);
    //创建通知
    NSNotification *notification =[NSNotification notificationWithName:@"TUISONGTONGZHI" object:nil userInfo:nil];
    //通过通知中心发送通知
    [[NSNotificationCenter defaultCenter] postNotification:notification];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 0x25 && buttonIndex == 1) {
    } else {
        postNotification(@"refreshHome");
    }
}

#pragma mark - GeTuiSdkDelegate
/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    // [4-EXT-1]: 个推SDK已注册，返回clientId
    NSLog(@">>>SDK启动成功返回:%@\n\n", clientId);
    [GeTuiSdk runBackgroundEnable:YES];
    [GeTuiSdk setPushModeForOff:NO];
}

/** SDK收到透传消息回调 */
- (void)GeTuiSdkDidReceivePayload:(NSString *)payloadId andTaskId:(NSString *)taskId andMessageId:(NSString *)aMsgId andOffLine:(BOOL)offLine fromApplication:(NSString *)appId {
    // [4]: 收到个推消息
    JLLog(@"--------------------------- 透传回调 推送来啦 ----------------------------");
    NSData* payload = [GeTuiSdk retrivePayloadById:payloadId];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:payload options:NSJSONReadingAllowFragments error:nil];
    if (![[dic objectForKey:@"title"] isEqualToString:@""] && [dic objectForKey:@"title"] != nil && [dic objectForKey:@"title"] != NULL) {
        UIAlertView *alert =[[UIAlertView alloc] initWithTitle:[dic objectForKey:@"title"] message:[dic objectForKey:@"content"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 0x25;
        [alert show];
    }
}

/** SDK遇到错误回调 */
- (void)GeTuiSdkDidOccurError:(NSError *)error {
    // [EXT]:个推错误报告，集成步骤发生的任何错误都在这里通知，如果集成后，无法正常收到消息，查看这里的通知。
    NSLog(@"\n>>>[GexinSdk error]:%@\n\n", [error localizedDescription]);
}

/** SDK收到sendMessage消息回调 */
- (void)GeTuiSdkDidSendMessage:(NSString *)messageId result:(int)result {
    // [4-EXT]:发送上行消息结果反馈
    NSString *record = [NSString stringWithFormat:@"Received sendmessage:%@ result:%d", messageId, result];
    NSLog(@"%@",record);
}


/** SDK运行状态通知 */
- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)aStatus {
    // [EXT]:通知SDK运行状态
}

//SDK设置推送模式回调
- (void)GeTuiSdkDidSetPushMode:(BOOL)isModeOff error:(NSError *)error {
    if (error) {
        [NSString stringWithFormat:@">>>[SetModeOff error]: %@", [error localizedDescription]];
    }
}

#pragma mark - UNUserNotificationCenterDelegate
//仅当应用程序在前台时，才会在代理上调用该方法
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    //1. 处理通知
    //初始化通知
   /* UNMutableNotificationContent *noContent = [[UNMutableNotificationContent alloc] init];
    noContent.title = @"久乐";//标题
    //noContent = @"XXXXXXXXX";副标题
    noContent.body = @"你有一条新消息";//正文
    noContent.badge = @1;
    UNNotificationSound *sound = [UNNotificationSound defaultSound];
    noContent.sound = sound;
    noContent.categoryIdentifier = @"uid";
    UNTimeIntervalNotificationTrigger *trigger1 = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.1 repeats:NO];
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"push" content:noContent trigger:trigger1];
    //通知
    UNUserNotificationCenter *cente = [UNUserNotificationCenter currentNotificationCenter];
    [cente addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        NSLog(@"%@  error",error);
        
    }];*/
    //2. 处理完成后条用 completionHandler ，用于指示在前台显示通知的形式
    completionHandler(UNNotificationPresentationOptionAlert);
}

#pragma mark - background fetch  唤醒
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    //重置角标
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    /// Background Fetch 恢复SDK 运行p
    [GeTuiSdk resume];
    completionHandler(UIBackgroundFetchResultNewData);
}


- (void)applicationWillResignActive:(UIApplication *)application {
    //重置角标
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    JLLog(@"app status : %zd , %s",[UIApplication sharedApplication].applicationState , __FUNCTION__);
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    isBackGround = YES;
    JLLog(@"app status : %zd , %s",[UIApplication sharedApplication].applicationState , __FUNCTION__);

}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    isBackGround = NO;
    JLLog(@"app status : %zd , %s",[UIApplication sharedApplication].applicationState , __FUNCTION__);
}

- (void)applicationDidBecomeActive:(UIApplication *)application {

    JLLog(@"app status : %zd , %s",[UIApplication sharedApplication].applicationState , __FUNCTION__);
}

- (void)applicationWillTerminate:(UIApplication *)application {
    JLLog(@"app status : %zd , %s",[UIApplication sharedApplication].applicationState , __FUNCTION__);
}

#pragma 友盟分享 U-Share SDK回调
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    if (self.orderType ==nil ||self.orderId ==nil) {
        BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
        return result;
    }else{
        if ([self.orderType isEqualToString:@"1"]){
            [[NSNotificationCenter defaultCenter]postNotificationName:@"pushToOrderVC" object:nil];
        }
        _timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(requestData) userInfo:nil repeats:YES];
    }
    return YES;
}

#pragma 微信支付相关方法
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return  [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
}
// NOTE: 9.0以后使用新API接口
- (void)requestData{
    NSMutableDictionary *params = [NSMutableDictionary new];
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
    NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"token"];
    [params setObject:self.orderId forKey:@"orderid"];
    [params setObject:self.orderType forKey:@"order_type"];
    [params setObject:userId forKey:@"user_id"];
    [params setObject:token forKey:@"token"];
    [MallRequestManager post:@"ShoppingMall/checkorder" RequestParams:params  FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) {
            NSLog(@"error:%@",connectionError);
            [SVProgressHUD showErrorWithStatus:@"网络连接错误"];
        }else{
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            if ([self.orderType isEqualToString:@"2"]) {
                NSDictionary *dict =  [dic objectForKey:@"result"];
                if ([[dic objectForKey:@"message"]isEqualToString:@"支付成功"]) {
                    NSString *type =  [dict objectForKey:@"type"];
                    if ([type isEqualToString:@"1"]) {
                        [self performSelectorOnMainThread:@selector(FromRenewalsVCPushHistoryVC) withObject:nil waitUntilDone:YES];
                    }
                    if ([type isEqualToString:@"2"]) {
                        [self performSelectorOnMainThread:@selector(FromRoamingVCPushHistoryVC) withObject:nil waitUntilDone:YES];
                    }
                }
            }
            [SVProgressHUD showSuccessWithStatus:[dic objectForKey:@"message"]];
            [_timer invalidate];
            self.orderId = nil;
            self.orderType = nil;
        }
    }];
}

- (void)FromRoamingVCPushHistoryVC{
     [[NSNotificationCenter defaultCenter]postNotificationName:@"FromRoamingVCPushHistoryVC" object:nil];
}

- (void)FromRenewalsVCPushHistoryVC{
     [[NSNotificationCenter defaultCenter]postNotificationName:@"FromRenewalsVCPushHistoryVC" object:nil];
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options{
    if (self.orderType ==nil ||self.orderId ==nil) {
        BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
        return result;
    }else{
        if ([self.orderType isEqualToString:@"1"]){
            [[NSNotificationCenter defaultCenter]postNotificationName:@"pushToOrderVC" object:nil];
        }
        _timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(requestData) userInfo:nil repeats:YES];
    }
    return YES;
}

@end
